/**
 * @Author: songgh
 * @Date: 2021-09-20 14:41:08
 * @LastEditors: songgh
 * @LastEditTime: 2021-09-20 15:41:08
 * @Description: 服务查询
 */
import { defineComponent, reactive, watch, watchEffect } from "vue";
import { default as dayjs, Dayjs } from "dayjs";
import { useStore } from "vuex";
import { serviceSearch } from "@src/api";
import router from "@src/router";
import { RouterLink } from "vue-router";
import { Toast } from "vant";

interface IList {
  id?: string;
  serviceImg?: string;
  serviceTitle?: string;
  serviceType?: string;
  serviceDate?: string;
}

interface IState {
  serviceDate?: Dayjs;
  isCalendarShow?: boolean;
  week?: string[];
  colors?: string[];
  selectDateIdx?: number;
  dataList?: Array<IList>;
  loading?: boolean;
  finished?: boolean;
  totalElements?: number;
  currentPage?: number;
  pageSize?: number;
  timer?: null | number;
  scroll?: number;
}

export default defineComponent({
  name: "ServiceList",
  setup() {
    const state = reactive<IState>({
      serviceDate: dayjs(),
      isCalendarShow: false,
      week: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      colors: [`rgb(39,186,107)`, `rgb(159,55,191)`, `rgb(43,137,188)`, `rgb(189,112,48)`],
      selectDateIdx: 0,
      dataList: [],
      loading: false,
      finished: false,
      totalElements: 0,
      currentPage: 0,
      pageSize: 8,
      timer: null,
      scroll: 0
    });

    const store = useStore();
    const { userName } = store.getters["user/getUserInfo"];

    const onConfirm = date => {
      state.isCalendarShow = false;
      state.serviceDate = dayjs(date);
    }

    const onSearch = async (page = 0, size = state.pageSize) => {
      try {
        Toast.loading({ message: '加载中...', forbidClick: true, });
        const timeStampStart = state.serviceDate.unix().toString();
        // const timeStampEnd = state.serviceDate.add(1,'day').unix().toString();

          const { content: serviceList, totalElements } = await serviceSearch({ planner: userName, serviceTimeFrom: timeStampStart, mobile: "是", page: `${page}`, size: `${size}` });
        state.totalElements = totalElements ? totalElements : 0;
        state.dataList = [...state.dataList, ...serviceList.map(service => ({
          id: service?.id,
          serviceImg: service?.imgIds?.length > 0 ? service?.imgIds[0] : '',
          serviceTitle: service?.content,
          serviceType: service?.serviceType,
          serviceDate: dayjs(service?.serviceStartTime).format('YYYY-MM-DD')
        }))];
      } catch (error) {
        console.error(error);
      }
    }

    const onLoad = async () => {
      state.loading = true;
      if (state.currentPage * state.pageSize < state.totalElements) {
        state.currentPage++;
        await onSearch(state.currentPage)
      } else {
        state.finished = true;
      }
      state.loading = false;
    };

    watchEffect(() => {
      state.selectDateIdx = state.serviceDate.day();
    });

    watch(() => state.serviceDate, (date, preDate) => {
      if (date.format('YYYY-MM-DD') !== preDate.format('YYYY-MM-DD')) {
        if (state.timer) {
          clearTimeout(state.timer);
        }
        state.timer = setTimeout(async () => {
          state.dataList = [];
          state.currentPage = 0;
          await onSearch();
        }, 500);
      }
    });

    onSearch();

    return {
      state,
      onConfirm,
      onLoad,
      router,
      store,
    }
  },
  // @ts-ignore
  beforeRouteLeave(to, from, next) {
    this.state.scroll = (this.$refs.serviceList as Element).scrollTop;
    next();
  },
  // @ts-ignore
  // beforeRouteEnter(to, from, next) {
  //   next(vm=>{
  //     if (!/^\/service\-detail\/[a-zA-Z0-9]+$/.test(from.path)) {
  //       // @ts-ignore
  //       vm.state.scroll = 0;
  //       // @ts-ignore
  //       vm.state.serviceDate = dayjs();
  //     }
  //   });
  // },
  activated() {
    // @ts-ignore
    this.$refs.serviceList.scrollTop = this.state.scroll;
  },
  render() {
    return (
      <div>
        <shell title="服务信息查询" v-slots={{
          default: () => (
            <div ref="serviceList" class="overflow-y-scroll h-full">
              <div class="date-selector p-3 bg-white">
                <div class="flex justify-between text-xs">
                  <span class="font-semibold" onClick={() => this.state.isCalendarShow = true}>{dayjs(this.state.serviceDate).format("YYYY年MM月")}</span>
                  <div>
                    <span class="font-normal text-gray-600" onClick={() => { this.state.serviceDate = dayjs(); this.state.selectDateIdx = dayjs().day() }}>回到当日</span>
                    {/*
                      <span class="font-semibold ml-6">
                        按周查看
                        <van-icon class-prefix={`text-black iconfont icon-paixu ml-1`} size="0.1rem" name="extra" />
                      </span>
                    */}
                  </div>
                </div>
                <div class="flex justify-between items-center text-xs pt-4">
                  {
                    this.state.week.map((item, index) => {
                      const serviceDate: Dayjs = dayjs(this.state.serviceDate);
                      let date: Dayjs = serviceDate;
                      let dateDay: number = 0;

                      if (serviceDate.day() > index) {
                        date = serviceDate.subtract(serviceDate.day() - index, 'day');
                        dateDay = date.date();
                      } else if (serviceDate.day() < index) {
                        date = serviceDate.add(index - serviceDate.day(), 'day');
                        dateDay = date.date();
                      } else {
                        dateDay = serviceDate.date();
                      }

                      const flag = date.unix() <= dayjs().unix();

                      return (<div class={['flex', 'flex-col', 'justify-between', 'items-center']} onClick={() => { if (flag) { this.state.serviceDate = date; this.state.selectDateIdx = index; } }}>
                        <span class={["pb-2", ...(this.state.selectDateIdx === index ? ['font-semibold', "text-black"] : ["text-gray-500", "font-normal"])]}>{date.format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD') ? "今天" : item}</span>
                        <span class={["font-semibold", "w-6", "h-6", "text-center", 'leading-6', "rounded", 'transition-all', ...(this.state.selectDateIdx === index ? ['bg-gray-600', 'text-white'] : []), ...(flag ? [] : ['text-gray-500'])]}>{dateDay}</span>
                      </div>)
                    })
                  }
                </div>
              </div>
              <van-list
                class="m-3"
                v-model:modelValue={this.state.loading}
                v-model:finished={this.state.finished}
                finished-text="没有更多了"
                onLoad={this.onLoad}
              >
                {
                  this.state.dataList.map(item => {
                    let idx = 0;
                    switch (item.serviceType) {
                      case "专业咨询": { idx = 0; break; }
                      case "技术把控": { idx = 1; break; }
                      case "沟通协调": { idx = 2; break; }
                      case "宣传服务": { idx = 3; break; }
                      default: break;
                    }
                    const color = this.state.colors[idx];

                    return (
                      <RouterLink to={{name:"ServiceForm", query:{ id:item.id}}}>
                        <div class="mb-3 bg-white p-3 rounded-md flex relative">
                          <van-image
                            width="4.5rem"
                            height="4.5rem"
                            fit="cover"
                            src={item.serviceImg}
                          />
                          <div class="ml-3 flex flex-col justify-between">
                            <span class="text-sm truncate" style={{ width: '11em' }}>{item.serviceTitle}</span>
                            <span class={["text-gray-500", "text-xs"]}>{item.serviceDate}</span>
                          </div>
                          <span class={["absolute", "right-3", "bottom-3", "rounded-sm", "text-xs", "px-2", 'py-0.5']} style={{ 'background-color': color.replace(/^rgb\((\d*),(\d*),(\d*)\)$/, "rgba($1,$2,$3,.2)"), 'color': color }}>{item.serviceType}</span>
                        </div>
                      </RouterLink>
                    )
                  })
                }
              </van-list>
              <van-calendar v-model:show={this.state.isCalendarShow} onConfirm={this.onConfirm} min-date={new Date(1970, 1, 1)} max-date={new Date()} default-date={new Date(this.state.serviceDate.format('YYYY,MM,DD'))} round={false} position="right" />
            </div>
          )
        }}>
        </shell>
      </div>
    );
  }
});
